package com.boco.base.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.util.Base64;

import com.orhanobut.logger.Logger;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * 创建人： caodailu
 * 创建时间：2016/8/24 0024
 * 邮箱：caodailu@boco.com.cn
 */
public class Base64Utils {

    public static String path2Base64Str(String path) {
        if (path == null) {
            return null;
        }

        path = path.substring(7);
        String suffix = getSuffix(path);
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inPreferredConfig = Bitmap.Config.RGB_565;
            Bitmap bitmap = ImageCompressL(BitmapFactory.decodeFile(path,options));
            ByteArrayOutputStream op = new ByteArrayOutputStream();
            if (suffix.equals("jpg") || suffix.equals("jpeg"))
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, op);
            else if (suffix.equals("png"))
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, op);
            byte[] bytes = op.toByteArray();
            String str = Base64.encodeToString(bytes, Base64.DEFAULT);
            Logger.e(str.length()+"字节");
            op.close();
            return str;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private static String getSuffix(String str) {

        String[] d = str.split("\\.");
        return d[d.length - 1];

    }


    /**
     * 如果图片大小大于64k就压缩
     * @param bitmap
     * @return
     */
    private static Bitmap ImageCompressL(Bitmap bitmap) {
        double targetwidth = Math.sqrt(64.00 * 1000);
        if (bitmap.getWidth() > targetwidth || bitmap.getHeight() > targetwidth) {
            // 创建操作图片用的matrix对象
            Matrix matrix = new Matrix();
            // 计算宽高缩放率
            double x = Math.max(targetwidth / bitmap.getWidth(), targetwidth
                    / bitmap.getHeight());
            // 缩放图片动作
            matrix.postScale((float) x, (float) x);
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                    bitmap.getHeight(), matrix, true);
        }
        return bitmap;
    }
}
